package com.kupal.ahk;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.basic.BasicBorders;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author Kupal 3kb
 *         01.10.2011
 */
public class ClipboardUtil {

    public static Image getClipboard() throws IOException, UnsupportedFlavorException {
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

        if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            return (Image) t.getTransferData(DataFlavor.imageFlavor);
        }
        return null;
    }

    public static JFrame run(final String baseImageDir, String startFileName) {
        final JFrame frame = new JFrame("Clipborder");
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton("Flush");
        button.setBounds(0, 30, 80, 40);
        button.setVisible(true);
        JTextField input = new JTextField(startFileName);
        input.setBounds(0, 0, 80, 15);
        input.setBorder(BasicBorders.getTextFieldBorder());
        JTextArea area = new JTextArea();

        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                JTextField component = getComponent(frame, 1);

                String fileName = component.getText() + ".png";
                String pathToFile = baseImageDir + File.separator + fileName;
                JTextArea textArea = getComponent(frame, 2);
                textArea.setText("");
                try {
                    BufferedImage image = (BufferedImage) getClipboard();
                    File file = new File(pathToFile);
                    if(!file.exists()) {
                        boolean created = file.createNewFile();
                        if(!created) {
                            writeMessage(textArea, "File " + fileName + " didn't created");
                        }
                    }
                    ImageIO.write(image, "png", file);
                    writeMessage(textArea, "Image " + fileName + " saved.");
                    incrementFileName(component);
                    changeImage(frame, pathToFile);
                } catch (IOException e) {
                    writeMessage(textArea, "Can't write image: " + e.getMessage());
                } catch (UnsupportedFlavorException e) {
                    writeMessage(textArea, "Can't read from clipboard: " + e.getMessage());
                }
            }
        };

        button.addActionListener(actionListener);

        panel.add(button, BorderLayout.NORTH);
        panel.add(input, BorderLayout.NORTH);
        panel.add(area, BorderLayout.SOUTH);

        frame.add(panel, 0);
        frame.setSize(700,400);
        frame.setVisible(true);
        frame.setAlwaysOnTop(true);

        return frame;
    }

    private static void changeImage(JFrame frame, String pathToFile) {
        JPanel panel = (JPanel)frame.getContentPane().getComponent(0);
        ImagePanel imagePanel = new ImagePanel(pathToFile);
        if(panel.getComponentCount() == 4) {
            panel.remove(3);
        }
        panel.add(imagePanel, BorderLayout.EAST, 3);
    }

    private static void incrementFileName(JTextField component) {
        String originText = component.getText();
        String[] parts = originText.split("\\.");
        int num = Integer.parseInt(parts[1]);
        num++;
        component.setText(parts[0] + "." + (num < 10 ? "00" : (num < 100 ? "0" : "")) + num);
    }

    private static void writeMessage(JTextArea area, String message) {
        area.setText(area.getText() + "\n" + message);
    }

    private static <T extends Component> T getComponent(JFrame frame, int index) {
        return (T)((JPanel)frame.getContentPane().getComponent(0)).getComponent(index);
    }
}

class ImagePanel extends JPanel {

  private Image img;

  public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
  }

  public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }

  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  }
}